import cv2
import numpy as np
import Moudle as m
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume


##############################################
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(
    IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface,POINTER(IAudioEndpointVolume))
volrange = volume.GetVolumeRange()
minvol = volrange[0]
maxvol = volrange[1]
##############################################

cap = cv2.VideoCapture(0)
cap.set(3,1280)
cap.set(4,720)
detector = m.HandDetector()
volBar = 400
volPer = 0
vol = 0

while True:
    ret,frame = cap.read()
    pose_frame = detector.findHands(frame)
    lmlist = detector.findPosition(pose_frame)
    if len(lmlist) > 0:
        lentgh,cx,cy = detector.findgers((lmlist[4][1],lmlist[4][2]),(lmlist[8][1],lmlist[8][2]),frame)
        vol = np.interp(lentgh, [50, 300], [minvol, maxvol])
        volBar = np.interp(lentgh, [50, 300], [400, 150])
        # 进度条显示
        volPer = np.interp(lentgh, [50, 300], [0, 100])
        volume.SetMasterVolumeLevel(vol, None)
        if lentgh < 50:
            cv2.circle(frame, (cx, cy), 15, (0, 255, 0), 3)
    cv2.rectangle(frame, (50,150),(85,400),(0,255,0),3)
    cv2.rectangle(frame, (50,int(volBar)), (85,400), (0, 255, 0), cv2.FILLED)
    cv2.putText(frame, f"{int(volPer)}%", (40, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 3)
    cv2.imshow('frame',frame)
    cv2.waitKey(1)